/**
 * Created by uf040339 on 2016/9/7.
 */

(function ($, global) {
    $(function () {
        initLayout();

        setInterval(function () {
            digitClock();
        }, 1000);

        getSystemClock();

        setTimeout(function () {
            $('body').removeClass('loading');
        }, 1000);

        setInterval(function () {
            getSystemClock();
        }, 15000);

        $('#showHistory').on('click', function () {
            showHistorySelecterDialog();
        });
    });

    var showHistorySelecterDialog = function () {
        var dateObj = new Date(),
            YYYY = dateObj.getFullYear(),
            MM = (dateObj.getMonth() + 1),
            DD = dateObj.getDate(),
            todayDate;
        MM = MM < 10 ? '0' + MM : MM;
        DD = DD < 10 ? '0' + DD : DD;
        todayDate = YYYY + '-' + MM + '-' + DD;
        var d = dialog({
            fixed: true,
            title: 'Please Input Date',
            content: '<div><input type="text" style="width:320px;" class="form-control" id="dateIpt" value="' + todayDate + '" placeholder="Please input Date, e.g.:' + todayDate + '"></div>',
            okValue: 'OK',
            ok: function () {
                var $dateIpt = $('#dateIpt'),
                    dateStr = $dateIpt.val(),
                    datePtn = new RegExp('^\\d{4}\\-\\d{1,2}\\-\\d{1,2}$');
                dateStr = $.trim(dateStr);
                if (datePtn.test(dateStr)) {
                    showHistoryDataDialog(dateStr);
                }
                else {
                    alert('Date format error! Please input again.');
                    return false;
                }
            }
        });

        new Pikaday({
            field: document.getElementById('dateIpt'),
            firstDay: 1,
            format: 'YYYY-MM-DD',
            theme: 'dark-theme',
            minDate: new Date(2000, 1, 1),
            maxDate: new Date(2020, 12, 31),
            yearRange: [2000, 2020]
        });

        d.showModal();
    };

    var showHistoryDataDialog = function (dateStr) {
        var ptn = new RegExp('(\\d{4})[\\- ](\\d{1,2})[\\- ](\\d{1,2})'),
            dateNum = dateStr.replace(ptn, '$1$2$3');
        var weekDayNum = new Date(dateStr).getDay(),
            weekDayDict = {
                '0': 'Sun',
                '1': 'Mon',
                '2': 'Tue',
                '3': 'Wed',
                '4': 'Thu',
                '5': 'Fri',
                '6': 'Sat'
            },
            weekEn = '';
        if (weekDayNum != undefined) {
            weekEn = weekDayDict[weekDayNum];
        }

        var line_name = global.line_name;
        var d = dialog({
            fixed: true,
            title: 'Cylinder Case-' + line_name + '    ' + dateStr + ' ' + weekEn,
            content: '<iframe src="/NEP/PSS/api/history?line_name=' + line_name + '&date=' + dateNum + '" scrolling="no" frameborder="0" width="600" height="465"></iframe>'
        });
        d.show();
    };

    var getDateInfoDict = function () {
        var dateObj = new Date(),
            YYYY = dateObj.getFullYear(),
            MM = (dateObj.getMonth() + 1),
            DD = dateObj.getDate(),
            HH = dateObj.getHours(),
            mm = dateObj.getMinutes(),
            ss = dateObj.getSeconds();
        MM = MM < 10 ? '0' + MM : MM;
        DD = DD < 10 ? '0' + DD : DD;
        HH = HH < 10 ? '0' + HH : HH;
        mm = mm < 10 ? '0' + mm : mm;
        ss = ss < 10 ? '0' + ss : ss;
        return {
            year: YYYY,
            month: MM,
            day: DD,
            hour: HH,
            minute: mm,
            second: ss
        }
    };

    var digitClock = function () {
        var $timeBox = $('#currentTime'),
            dateStr;
        var dateInfoDict = getDateInfoDict();
        dateStr = dateInfoDict['year'] + '-' + dateInfoDict['month'] + '-' + dateInfoDict['day'] + ' ' + dateInfoDict['hour'] + ':' + dateInfoDict['minute'] + ':' + dateInfoDict['second'];
        $timeBox.text(dateStr);
    };

    var initLayout = function () {
        var winWidth = $(window).width(),
            winHeight = $(window).height(),
            $sL = $('#screenLeft'),
            $sR = $('#screenRight'),
            slphHt = $sL.find('.panel-heading').outerHeight(),
            srphHt = $sR.find('.panel-heading').outerHeight(),
            slpbWt = winWidth - $sR.width(),
            slpbHt = winHeight - slphHt,
            graphicWHRatio = 1.5;
        if (global.line_name == 'Z6') {
            graphicWHRatio = 132 / 100;
        }

        $('#pageContainer').width(winWidth);
        $sL.width(slpbWt);
        $sL.find('.panel-body').height(winHeight - slphHt);
        $sR.find('.panel-body').height(winHeight - srphHt);

        // 现只考虑 "图片预览面积的长宽比" < "图片的长宽比"
        var slpWTRatio = slpbWt / slpbHt;

        // for flexable
        var graphicWt = slpbWt - 20,
            graphicHt = graphicWt / graphicWHRatio;

        $('.graphic-layer').width(graphicWt).height(graphicHt)
        //.css({
        //    'marginTop': (slpbHt - graphicHt) * .5 + 'px'
        //})
        ;
    };

    var currentShiftNum = null;

    var timeStrToInt = function (timeStr) {
        var result = 0;
        if (timeStr) {
            var ptn = new RegExp("[:\\s\\-]", "g");
            result = parseInt(timeStr.replace(ptn, ''));
        }
        return result;
    };

    // 获取当前时间的班次数值，用于解决班次数据提前显示的问题
    var getShiftNum = function (resp) {
        var dateInfoDict = getDateInfoDict();
        var currentTimeStr = dateInfoDict['year'] + '' + dateInfoDict['month'] + dateInfoDict['day'] + dateInfoDict['hour'] + dateInfoDict['minute'] + dateInfoDict['second'];
        var currentTimeVal = parseInt(currentTimeStr);
        var s1 = timeStrToInt(resp['StartTime1']),
            s2 = timeStrToInt(resp['StartTime2']),
            s3 = timeStrToInt(resp['StartTime2']),
            e1 = timeStrToInt(resp['EndTime1']),
            e2 = timeStrToInt(resp['EndTime2']),
            e3 = timeStrToInt(resp['EndTime3']);
        if (currentTimeVal >= s1 && currentTimeVal < e1) {
            currentShiftNum = 1;
        }
        else if (currentTimeVal >= s2 && currentTimeVal < e2) {
            currentShiftNum = 2;
        }
        else if (currentTimeVal >= s3 && currentTimeVal < e3) {
            currentShiftNum = 3;
        }
        else {
            currentShiftNum = null;
            throw new Error('The shift info do not existed in the database.');
        }
    };

    var fillLineInfo = function (resp, codeVal) {

        if (resp['S' + codeVal]) $('#iptS' + codeVal).html(resp['S' + codeVal]);
        if (resp['E' + codeVal]) $('#iptE' + codeVal).html(resp['E' + codeVal]);

        if (/\d+/.test(resp['TargetOutput' + codeVal])) $('#targetOutput' + codeVal).html(resp['TargetOutput' + codeVal]);
        if (/\d+/.test(resp['TargetInput' + codeVal])) $('#targetInput' + codeVal).html(resp['TargetInput' + codeVal]);
        // 如果 target 值为 0 ，则 current 设置为0（即使有值）
        if (resp['TargetOutput' + codeVal] > 0 && currentShiftNum >= codeVal) {
            if (resp['CurrentOutput' + codeVal]) {
                var $currentOutput = $('#currentOutput' + codeVal);
                $currentOutput.html(resp['CurrentOutput' + codeVal]);
                if (resp['PlannedOutput' + codeVal] > resp['CurrentOutput' + codeVal]) {
                    $currentOutput.addClass('text-danger');
                }
                else {
                    $currentOutput.removeClass('text-danger');
                }
            }
            if (resp['CurrentInput' + codeVal]) {
                var $currentInput = $('#currentInput' + codeVal);
                $currentInput.html(resp['CurrentInput' + codeVal]);
                if (resp['PlannedInput' + codeVal] > resp['CurrentInput' + codeVal]) {
                    $currentInput.addClass('text-danger');
                }
                else {
                    $currentInput.removeClass('text-danger');
                }
            }
            if (resp['ForecastOutput' + codeVal]) {
                var $forecastOutput = $('#forecastOutput' + codeVal);
                $forecastOutput.html(resp['ForecastOutput' + codeVal]);
                if (resp['TargetOutput' + codeVal] > resp['ForecastOutput' + codeVal]) {
                    $forecastOutput.addClass('text-danger');
                }
                else {
                    $forecastOutput.removeClass('text-danger');
                }
            }
            if (resp['ForecastInput' + codeVal]) {
                var $forecastInput = $('#forecastInput' + codeVal);
                $forecastInput.html(resp['ForecastInput' + codeVal]);
                if (resp['TargetInput' + codeVal] > resp['ForecastInput' + codeVal]) {
                    $forecastInput.addClass('text-danger');
                }
                else {
                    $forecastInput.removeClass('text-danger');
                }
            }
            if (resp['PlannedOutput' + codeVal]) {
                var $plannedOutput = $('#plannedOutput' + codeVal);
                $plannedOutput.html(resp['PlannedOutput' + codeVal]);

                if (resp['CurrentOutput' + codeVal]) {
                    var $cpCut = $('#cpCutOutput' + codeVal),
                        cpCutVal = parseInt(resp['CurrentOutput' + codeVal]) - parseInt(resp['PlannedOutput' + codeVal]);
                    $cpCut.html(cpCutVal);
                    if (cpCutVal < 0) {
                        $cpCut.addClass('text-danger');
                    }
                    else {
                        $cpCut.removeClass('text-danger');
                    }
                }
            }
            if (resp['PlannedInput' + codeVal]) {
                var $plannedInput = $('#plannedInput' + codeVal);
                $plannedInput.html(resp['PlannedInput' + codeVal]);

                if (resp['CurrentInput' + codeVal]) {
                    var $cpCut = $('#cpCutInput' + codeVal),
                        cpCutVal = parseInt(resp['CurrentInput' + codeVal]) - parseInt(resp['PlannedInput' + codeVal]);
                    $cpCut.html(cpCutVal);
                    if (cpCutVal < 0) {
                        $cpCut.addClass('text-danger');
                    }
                    else {
                        $cpCut.removeClass('text-danger');
                    }
                }
            }
        }
    };

    var getSystemClock = function () {
        var data = {
            rand: Date.now()
        };
        if (global.line_name) data['line_name'] = global.line_name;
        $.get('/NEP/PSS/api/product_info', data, function (resp) {
            if (resp) {
                getShiftNum(resp);
                var codeArr = [1, 2, 3];
                $.each(codeArr, function (idx, code) {
                    fillLineInfo(resp, code);
                });
            }
        }, 'json');
    };

    $(window).on('resize', function () {
        initLayout();
    });
})(jQuery, window);
